//
// Created by thomas on 9/24/20.
//

#include <event2/thread.h>
#include <event.h>
#include <stdlib.h>
#include <libevent_socket_wrapper.h>
#include <debug.h>

#define MESSAGE_DELIMITER   "$$"    /*TCP数据包的分隔符*/

evsocket_config_ts config;
evsocket_result_ts result;
struct event_base *evbase;

/*length参数必须用到，因为evbuffer_pullup得到的线性buffer不会保证有'\0'结束符*/
int recv_msg(struct bufferevent *bev, char *buf, unsigned int length)
{
//    DEBUG_PRINTF(INFO, "%s", buf);
    printf("%s\n", buf);
    return 0;
}

static int connect_event_callback(struct bufferevent *bev, short events, void *args)
{
    DEBUG_PRINTF(INFO, "socket event 0x%x", events);
    if (events & BEV_EVENT_CONNECTED)
    {

    }
    else if (events & BEV_EVENT_EOF)
    {
        DEBUG_PRINTF(ERROR, "socket closed");
    }
    else if (events & BEV_EVENT_ERROR)
    {
        DEBUG_PRINTF(ERROR, "unrecoverable error encountered");
    }

    return 0;
}

_Noreturn void *foo(void *args)
{
    while (1)
    {
        sleep(1);
//        evsocket_write(&config, &result, config.bev, "abc", 3);
    }
}

int main(void)
{
    pthread_t tid;
    //需要支持多线程
    evthread_use_pthreads();
    evbase = event_base_new();
    if (evbase == NULL)
    {
        exit(-1);
    }

    if (EVSOCKET_OK != evsocket_init_as_inet_server(&config,
                                                    true,
                                                    "/home/thomas/myca/keys/ca.crt",
                                                    "/home/thomas/myca/keys/myserver.crt",
                                                    "/home/thomas/myca/keys/myserver.key",
                                                    "127.0.0.1",
                                                    5707,
                                                    recv_msg,
                                                    NULL,
                                                    connect_event_callback,
                                                    MESSAGE_DELIMITER))
    {
        DEBUG_PRINTF(ERROR, "evsocket_init_as_inet_server failed");
        return -1;
    }

    if (EVSOCKET_OK != evsocket_create(&config, &result, evbase))
    {
        DEBUG_PRINTF(INFO, "evsocket_create failed:%d\n", result.status);
        if (EVSOCKET_OK != evsocket_release(&config, &result))
        {
            DEBUG_PRINTF(ERROR, "evsocket_release failed");
        }
        return -1;
    }

    pthread_create(&tid, NULL, foo, evbase);

    event_base_loop(evbase, EVLOOP_NO_EXIT_ON_EMPTY);

    evsocket_release(&config, &result);

    event_base_free(evbase);
    return 0;
}
